<template>
    <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeAvatarUpload"
        :http-request="uploadImage">
        <!--(自动上传) action=>上传地址 人资项目(手动上传) -->
        <!-- show-file-list 不展示列表 -->
        <img v-if="value" :src="value" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>
<script>
import COS from 'cos-js-sdk-v5';
export default {
    props: {
        value: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            imageUrl: ''
        };
    },
    methods: {
        //检查函数
        beforeAvatarUpload(file) {
            //支持jpeh png gif bmp格式
            const isJPG = ['image/jpeg', 'image/png', 'image/bmp', 'image/gif'].includes(file.type)
            const isLt2M = file.size / 1024 / 1024 < 5;//5M
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return isJPG && isLt2M;
        },
        uploadImage(file) {
            console.log(file.file);
            const cos = new COS({
                // 必选参数
                SecretId: 'AKIDVt56wb3HH3bw3wcAVpxudBYknfKn47yc',
                SecretKey: 'e7OSIvOfjZEg2B6nKgqeKp6Zt0vd7OSV',
            });
            cos.putObject({
                Bucket: 'gebulinchengxuyuan-1334696410',// 存储桶名称
                Region: 'ap-guangzhou',// 存储桶所在地域
                Key: file.file.name, // 上传文件名`
                StorageClass: 'STANDARD', // 固定值
                Body: file.file, // 上传文件对象
            }, (err, data) => {
                if (data.statusCode === 200 && data.Location) {
                    this.$emit('input', 'http://' + data.Location);
                } else {
                    this.$message.error(err.Message);//上传失败提示
                }
            })
        }
    }
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
